package psn.qiuyiping.autocad.dxffile;

import java.io.IOException;
import java.lang.reflect.Member;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.cbf4file.ClassUtils;

public class DxfObject extends DefaultDxf0 {
    static final Map<String, Class<? extends DxfObject>> SUBCLASSFUNCS;
    final static Map<Integer, Member> FIELDS;

    static {
        SUBCLASSFUNCS = new java.util.TreeMap<>();
        registerPackage(DxfProcessContext.class.getPackage().getName());
        FIELDS = redo(DxfObject.class);
    }

    public static void registerPackage(String packName) {
        try {
            for (Class<?> cls : ClassUtils.getClasses(packName)) {
                SubClassName f = cls.getAnnotation(SubClassName.class);
                if (f == null) {
                    continue;
                }
                SUBCLASSFUNCS.put(f.value(), (Class<? extends DxfObject>) cls);
            }
        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
        }
    }

    DxfHandle    handle;
    @DxfCode(330)
    DxfHandle    owner;
    List<Object> reactors;

    @Override
    public Map<Integer, Member> initFields(){
        return new java.util.TreeMap<>(FIELDS);
    }

    @DxfCode(5)
    public void readHandle(DxfProcessContext context, DxfData<Object> item) {
        this.handle = (DxfHandle) item.getVal();
        context.getFile().addObject(handle, this);
    }

    @DxfCode(102)
    public void readDxf102(DxfProcessContext context, DxfData<Object> item) {
        String reactorName = (String) item.getVal();
        reactorName = reactorName.substring(1);
        if (reactors == null) {
            reactors = new LinkedList<>();
        }
        DxfReactor reactor = DxfReactor.getReator(reactorName);
        reactors.add(reactor);
        context.push(reactor);
    }

    @DxfCode(100)
    public void readSubClassName(DxfProcessContext context, DxfData<Object> item) {
        String subClsName = (String) item.getVal();
        Class<? extends DxfObject> cls = SUBCLASSFUNCS.get(subClsName);
        if(cls!=null){
            fields.putAll(redo(cls));
        }else{
            
        }
    }
}
